<?php
class EventosController extends AppController {
	public $scaffold;

	public function detalhe($id = null) {
		$this->Evento->id = $id;
		$this->set('evento', $this->Evento->read());
	}

	public function listarEventosJson(){
		$this->layout = 'ajax';

		$dateFormat = 'd/m/Y';

		// See the notes of the division by 1000 in the response, below.
		$fromTimestamp = $_POST['from'] / 1000;
		$toTimestamp = $_POST['to'] / 1000;
		
		$dateFrom = new DateTime("@$fromTimestamp");
		$dateTo = new DateTime("@$toTimestamp");

		if (isset($_GET['evento'])) {
			$eventId = $_GET['evento'];
		}
		
		$this->loadModel('Data');
		$conditions = array("Data.data BETWEEN ? AND ?" =>
				array(date_format($dateFrom, 'Y-m-d'), date_format($dateTo, 'Y-m-d'))
		);
		
		if (isset($eventId)) {
			$conditions['Data.evento_id'] = $eventId;
		}
		
		$datas = $this->Data->find('all', array('conditions' => $conditions));
		
		$arrayToReturn = array('success' => true, 'result' => null);
		$results = array();
		
		foreach ($datas as $data){
			$eventDate = new DateTime($data["Data"]["data"]);
			// Multiply by 1000 because time in javascript
			// is in milliseconds but in Unix is in seconds.
			// Reference: http://stackoverflow.com/a/847196/1574059
			//			https://github.com/Serhioromano/bootstrap-calendar/issues/8#issuecomment-19965216
			$eventJsTimestamp = $eventDate->format("U") * 1000; 
			// format("U") == timestamp
			
			array_push($results,
				array('id' => $data["Evento"]["id"],
					'title' => $data["Evento"]["nome"],
					'url' => Router::url(array('action' => 'detalhe', $data["Evento"]["id"])),
					'class' => "event-info",
					'start' => $eventJsTimestamp,
					'end' => $eventJsTimestamp
				)
			);
		}
		
		$arrayToReturn['result'] = $results;

		$this->set('json', json_encode($arrayToReturn));
		$this->render('json');
	}
}
?>